<template>
  <div id="app">
    <el-upload
      action
      accept=".xlsx, .xls"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFile"
    >
      <template #trigger>
        <el-button type="primary" style="margin-right: 10px"
          >打开excel</el-button
        >
      </template>
      <el-button type="success" @click="download">下载pdf</el-button>
    </el-upload>

    <div id="output" style="padding: 5px;"></div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx/xlsx.mjs";
import { downloadPDF } from "./tool.js";
import utils from "@/utils";
import { ElLoading } from 'element-plus'

//添加基础信息，如公司logo，公司名称
const companyLogo = ref(
  "https://static.wxb.com.cn/frontEnd/images/login-manager/header-logo.png"
);
const companyName = ref("心有灵犀科技股份有限公司");
const baseInfo =
  ref(`<img src="${companyLogo.value}" alt="logo" style="width: 115px;height: 32px;">
    <div style="display: flex;justify-content: center;"><div style="margin: 10px 0;font-weight: 700;font-size: 25px;">${companyName.value}</div></div>`);

const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file); //以二进制的方式读取
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};

let loadingInstance = null;
const handleFile = async (ev) => {
  let file = ev.raw;
  console.log(file);
  if (!file) {
    utils.alert("文件打开失败", "error");
    return;
  } else {
    const outputElement = document.getElementById("output");
    outputElement.innerHTML = baseInfo.value; //添加基础信息
    loadingInstance = ElLoading.service({
      text: "解析中...",
    });

    let data = await readFile(file);
    let workbook = XLSX.read(data, { type: "binary" }); //解析二进制格式数据
    const sheet_name_list = workbook.SheetNames; // 获取Sheets的名称
    let loadLoadingNum = sheet_name_list.length;

    for (let i = 0; i < sheet_name_list.length; i++) {
      setTimeout(() => {
        const sheetName = workbook.SheetNames[i];
        const sheet = workbook.Sheets[sheetName];
        const merges = sheet["!merges"] || [];
        console.log("sheet", sheet);
        console.log("二进制数据的解析:", workbook);
        let result = XLSX.utils.sheet_to_json(sheet, { header: 1 }); //json数据格式
        console.log("最终解析的 json 格式数据格式:", result);

        const newDiv = document.createElement("div")
        const sheet_tit = `<div style="display: flex;justify-content: left;"><div style="margin: 10px 0;font-size: 20px;">${sheet_name_list[i]}</div></div>`;
        let html =
          sheet_tit +
          '<table style="border-collapse: collapse;border: 1px solid #000; margin-bottom: 20px;">';

        result.forEach((row, rowIndex) => {
          html += "<tr>";
          row.forEach((cell, colIndex) => {
            let isMerged = false;
            for (let merge of merges) {
              if (merge.s.r === rowIndex && merge.s.c === colIndex) {
                let rowspan = merge.e.r - merge.s.r + 1;
                let colspan = merge.e.c - merge.s.c + 1;
                html += `<td style="border: 1px solid #000;" rowspan="${rowspan}" colspan="${colspan}">${
                  cell || ""
                }</td>`;
                isMerged = true;
                break;
              }
              // 跳过合并范围内的重复单元格
              if (
                rowIndex >= merge.s.r &&
                rowIndex <= merge.e.r &&
                colIndex >= merge.s.c &&
                colIndex <= merge.e.c
              ) {
                isMerged = true;
                break;
              }
            }
            if (!isMerged) {
              html += `<td style="border: 1px solid #000;">${cell || ""}</td>`;
            }
          });
          html += "</tr>";
        });

        html += "</table>";
        newDiv.innerHTML = html;
        document.getElementById("output").appendChild(newDiv);
        loadLoadingNum--;
        if (loadLoadingNum === 0) {
          loadingInstance.close()
          loadingInstance = null
        }
      },i * 800);
    }
  }
};

const pdfName = ref("test");
const download = () => {
  if (!document.getElementById("output").innerHTML) return utils.alert("请先打开excel文件", "error");

  utils.alert("正在生成PDF，请稍后...",'success');
  downloadPDF(document.querySelector("#output"), pdfName.value);
};
</script>
